

using Furion.JsonSerialization;
using Furion.Logging;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

namespace ciji.Core;

/// <summary>
/// 数据库日志写入器
/// </summary>
public class DatabaseLoggingWriter : IDatabaseLoggingWriter
{


    private SqlSugarRepository<sys_OperateLog> _logRep;
    // 任何数据库 ORM 注入。。。
    public DatabaseLoggingWriter(IHttpContextAccessor httpContextAccessor
        , SqlSugarRepository<sys_OperateLog> logRep)
    {

        _logRep = logRep;
    }

    public Task WriteAsync(LogMessage logMsg, bool flush)
    {
        var jsonStr = logMsg.Context?.Get("loggingMonitor")?.ToString();

        // 获取当前操作者
        var loggingMonitor = JSON.Deserialize<LoggingMonitorDto>(jsonStr);
        var userInfo = GetUserInfo(loggingMonitor);


        sys_OperateLog log = new sys_OperateLog
        {
            LoginId = userInfo.UserId,
            LoginName = userInfo.Name,
            LoginIp = logMsg.Context?.Get("localIPv4")?.ToString(),
            LoginTime = DateTime.Now,
            Message = logMsg.Context?.Get("requestUrl")?.ToString(),
            OperateName = logMsg.Context?.Get("displayName")?.ToString(),

        };
        return _logRep.InsertAsync(log);
    }




    /// <summary>
    /// 从日志消息中获取用户信息
    /// </summary>
    /// <param name="loggingMonitor"></param>
    /// <returns></returns>
    private LoggingUserInfo GetUserInfo(LoggingMonitorDto loggingMonitor)
    {
        LoggingUserInfo result = new();
     
        if (loggingMonitor.AuthorizationClaims != null)
        {
            result.UserId = loggingMonitor.AuthorizationClaims.Find(m => m.Type == ClaimConst.UserId)?.Value;
            result.Name = loggingMonitor.AuthorizationClaims.Find(m => m.Type == ClaimConst.Name)?.Value;
         
        }  
        return result;
    }

  
  
}